import React, { useState, useEffect } from 'react'
import { Card, Table, Button, Tag, Space, Modal, Form, Input, Select, message, Row, Col, Avatar } from 'antd'
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined, SearchOutlined } from '@ant-design/icons'

interface MediaContent {
  id: string
  title: string
  type: 'news' | 'video' | 'audio' | 'image'
  author: string
  publishDate: string
  status: 'draft' | 'published' | 'archived'
  village: string
  views: number
  likes: number
  comments: number
  content: string
}

const MediaIntegrationManagement: React.FC = () => {
  const [contents, setContents] = useState<MediaContent[]>([])
  const [loading, setLoading] = useState(true)
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [editingContent, setEditingContent] = useState<MediaContent | null>(null)
  const [searchText, setSearchText] = useState('')

  // mock数据 - 与用户端MediaIntegration页面关联
  useEffect(() => {
    const mockData: MediaContent[] = [
      {
        id: '1',
        title: '幸福村春季农业技术推广会',
        type: 'news',
        author: '张大山',
        publishDate: '2024-03-15',
        status: 'published',
        village: '幸福村',
        views: 1250,
        likes: 89,
        comments: 23,
        content: '幸福村成功举办春季农业技术推广会，吸引了众多村民参与...'
      },
      {
        id: '2',
        title: '智慧农业示范园建设进展',
        type: 'video',
        author: '李小花',
        publishDate: '2024-03-10',
        status: 'published',
        village: '和平村',
        views: 890,
        likes: 45,
        comments: 12,
        content: '智慧农业示范园建设进展顺利，预计6月底完工...'
      },
      {
        id: '3',
        title: '乡村文化节活动预告',
        type: 'image',
        author: '王老五',
        publishDate: '2024-03-05',
        status: 'draft',
        village: '富裕村',
        views: 0,
        likes: 0,
        comments: 0,
        content: '即将举办乡村文化节活动，欢迎村民踊跃参与...'
      },
      {
        id: '4',
        title: '智慧农业示范园建设进展',
        type: 'video',
        author: '农业技术员-王五',
        publishDate: '2024-03-12',
        status: 'published',
        village: '和平村',
        views: 980,
        likes: 67,
        comments: 15,
        content: '展示智慧农业示范园的最新建设进展和技术应用...'
      },
      {
        id: '5',
        title: '乡村文化节活动预告',
        type: 'news',
        author: '文化站-赵六',
        publishDate: '2024-03-15',
        status: 'published',
        village: '幸福村',
        views: 1120,
        likes: 78,
        comments: 21,
        content: '即将举办的乡村文化节活动预告和参与方式介绍...'
      },
      {
        id: '6',
        title: '农产品电商销售指南',
        type: 'news',
        author: '电商专家-钱七',
        publishDate: '2024-03-18',
        status: 'published',
        village: '富裕村',
        views: 1340,
        likes: 92,
        comments: 28,
        content: '帮助村民掌握农产品电商销售技巧和平台运营方法...'
      },
      {
        id: '7',
        title: '乡村传统手工艺展示',
        type: 'image',
        author: '手工艺人-孙八',
        publishDate: '2024-03-20',
        status: 'published',
        village: '和平村',
        views: 1670,
        likes: 145,
        comments: 42,
        content: '展示乡村传统手工艺的精湛技艺和文化价值...'
      },
      {
        id: '8',
        title: '乡村健康生活讲座',
        type: 'audio',
        author: '健康专家-周九',
        publishDate: '2024-03-22',
        status: 'published',
        village: '幸福村',
        views: 890,
        likes: 54,
        comments: 18,
        content: '关于乡村健康生活方式和疾病预防的专题讲座...'
      },
      {
        id: '9',
        title: '数字乡村建设成果展示',
        type: 'video',
        author: '数字乡村建设组',
        publishDate: '2024-03-25',
        status: 'published',
        village: '富裕村',
        views: 1560,
        likes: 112,
        comments: 35,
        content: '展示数字乡村建设的最新成果和未来规划...'
      },
      {
        id: '10',
        title: '乡村旅游资源介绍',
        type: 'image',
        author: '旅游发展办-吴十',
        publishDate: '2024-03-28',
        status: 'draft',
        village: '和平村',
        views: 0,
        likes: 0,
        comments: 0,
        content: '介绍乡村特色旅游资源和发展潜力...'
      }
    ]

    setTimeout(() => {
      setContents(mockData)
      setLoading(false)
    }, 1000)
  }, [])

  const columns = [
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      width: 200,
      render: (text: string, record: MediaContent) => (
        <div>
          <div style={{ fontWeight: 'bold', marginBottom: '4px' }}>{text}</div>
          <div style={{ fontSize: '12px', color: '#666' }}>{record.village}</div>
        </div>
      )
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (type: string) => {
        const typeMap = {
          news: { text: '新闻', color: 'blue' },
          video: { text: '视频', color: 'red' },
          audio: { text: '音频', color: 'green' },
          image: { text: '图片', color: 'orange' }
        }
        const config = typeMap[type as keyof typeof typeMap]
        return <Tag color={config.color}>{config.text}</Tag>
      }
    },
    {
      title: '作者',
      dataIndex: 'author',
      key: 'author',
      width: 100,
      render: (author: string) => (
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
          <Avatar size="small" style={{ backgroundColor: '#1890ff' }}>
            {author.charAt(0)}
          </Avatar>
          {author}
        </div>
      )
    },
    {
      title: '发布日期',
      dataIndex: 'publishDate',
      key: 'publishDate',
      width: 120
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => {
        const statusMap = {
          draft: { text: '草稿', color: 'orange' },
          published: { text: '已发布', color: 'green' },
          archived: { text: '已归档', color: 'gray' }
        }
        const config = statusMap[status as keyof typeof statusMap]
        return <Tag color={config.color}>{config.text}</Tag>
      }
    },
    {
      title: '互动数据',
      key: 'interaction',
      width: 150,
      render: (record: MediaContent) => (
        <div style={{ fontSize: '12px', color: '#666' }}>
          <div>浏览: {record.views}</div>
          <div>点赞: {record.likes} | 评论: {record.comments}</div>
        </div>
      )
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (record: MediaContent) => (
        <Space size="small">
          <Button type="link" size="small" icon={<EyeOutlined />}>预览</Button>
          <Button 
            type="link" 
            size="small" 
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button type="link" size="small" icon={<DeleteOutlined />} danger>删除</Button>
          {record.status === 'draft' && (
            <Button type="link" size="small">发布</Button>
          )}
        </Space>
      )
    }
  ]

  const handleAdd = () => {
    setEditingContent(null)
    setIsModalVisible(true)
  }

  const handleEdit = (record: MediaContent) => {
    setEditingContent(record)
    setIsModalVisible(true)
  }

  const handleSubmit = (values: any) => {
    if (editingContent) {
      // 编辑现有内容
      setContents(contents.map(item => 
        item.id === editingContent.id 
          ? { ...item, ...values }
          : item
      ))
      message.success('内容更新成功')
    } else {
      // 添加新内容
      const newContent: MediaContent = {
        id: Date.now().toString(),
        title: values.title,
        type: values.type,
        author: '管理员',
        publishDate: new Date().toISOString().split('T')[0],
        status: 'draft',
        village: values.village,
        views: 0,
        likes: 0,
        comments: 0,
        content: values.content
      }
      setContents([newContent, ...contents])
      message.success('内容添加成功')
    }
    setIsModalVisible(false)
  }

  const filteredContents = contents.filter(content =>
    content.title.toLowerCase().includes(searchText.toLowerCase()) ||
    content.village.toLowerCase().includes(searchText.toLowerCase()) ||
    content.author.toLowerCase().includes(searchText.toLowerCase())
  )

  return (
    <div style={{ padding: '24px', background: '#f5f5f5', minHeight: '100vh' }}>
      <Card 
        title="乡村媒体融合发布管理"
        extra={
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            添加内容
          </Button>
        }
      >
        {/* 搜索和筛选 */}
        <Row gutter={16} style={{ marginBottom: '16px' }}>
          <Col span={8}>
            <Input
              placeholder="搜索标题、村庄或作者"
              prefix={<SearchOutlined />}
              value={searchText}
              onChange={e => setSearchText(e.target.value)}
            />
          </Col>
          <Col span={8}>
            <Select placeholder="选择内容类型" style={{ width: '100%' }} allowClear>
              <Select.Option value="news">新闻</Select.Option>
              <Select.Option value="video">视频</Select.Option>
              <Select.Option value="audio">音频</Select.Option>
              <Select.Option value="image">图片</Select.Option>
            </Select>
          </Col>
          <Col span={8}>
            <Select placeholder="选择发布状态" style={{ width: '100%' }} allowClear>
              <Select.Option value="draft">草稿</Select.Option>
              <Select.Option value="published">已发布</Select.Option>
              <Select.Option value="archived">已归档</Select.Option>
            </Select>
          </Col>
        </Row>

        <Table
          loading={loading}
          columns={columns}
          dataSource={filteredContents}
          rowKey="id"
          pagination={{
            total: filteredContents.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => 
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条内容`
          }}
        />
      </Card>

      {/* 添加/编辑弹窗 */}
      <Modal
        title={editingContent ? '编辑内容' : '添加内容'}
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
        width={800}
      >
        <Form
          layout="vertical"
          initialValues={editingContent || {
            type: 'news',
            village: '幸福村'
          }}
          onFinish={handleSubmit}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="标题"
                name="title"
                rules={[{ required: true, message: '请输入标题' }]}
              >
                <Input placeholder="请输入内容标题" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="内容类型"
                name="type"
                rules={[{ required: true, message: '请选择内容类型' }]}
              >
                <Select placeholder="请选择内容类型">
                  <Select.Option value="news">新闻</Select.Option>
                  <Select.Option value="video">视频</Select.Option>
                  <Select.Option value="audio">音频</Select.Option>
                  <Select.Option value="image">图片</Select.Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="所属村庄"
                name="village"
                rules={[{ required: true, message: '请选择所属村庄' }]}
              >
                <Select placeholder="请选择所属村庄">
                  <Select.Option value="幸福村">幸福村</Select.Option>
                  <Select.Option value="和平村">和平村</Select.Option>
                  <Select.Option value="富裕村">富裕村</Select.Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="发布状态"
                name="status"
                rules={[{ required: true, message: '请选择发布状态' }]}
              >
                <Select placeholder="请选择发布状态">
                  <Select.Option value="draft">草稿</Select.Option>
                  <Select.Option value="published">已发布</Select.Option>
                  <Select.Option value="archived">已归档</Select.Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            label="内容详情"
            name="content"
            rules={[{ required: true, message: '请输入内容详情' }]}
          >
            <Input.TextArea rows={6} placeholder="请输入内容详情" />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" style={{ marginRight: '8px' }}>
              {editingContent ? '更新' : '添加'}
            </Button>
            <Button onClick={() => setIsModalVisible(false)}>
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default MediaIntegrationManagement